import pathlib
import time

from selenium import webdriver
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.by import By
from selenium.webdriver.edge.service import Service


class Douyin:
    def __init__(self):
        # 尝试传参
        s = Service("chromedriver.exe")
        self.driver = webdriver.Chrome(service=s)
        # driverfile_path = r'./msedgedriver.exe'
        # driver = webdriver.Edge(executable_path=driverfile_path)
        self.driver.maximize_window()  # 最大化窗口

    def prepare(self, video, desc):
        try:

            # 进入创作者页面，并上传视频
            self.driver.get("https://creator.douyin.com/creator-micro/home")
            time.sleep(2)

            e_login = self.driver.find_element(by=By.XPATH,
                                               value="//*[@id='root']/div/section/header/div[1]/div/div/div/div[2]/span")

            if e_login is not None:
                e_login.click()
                self.driver.implicitly_wait(1)
                self.do_login(video, desc)
            else:
                self.do_publish(video, desc)
        except Exception as e:
            print(e)
            self.driver.quit()

    def do_login(self, video, desc):
        # 切换手机号登录
        self.driver.find_element(by=By.XPATH,
                                 value="//*[@id='dialog-0']/div/div[2]/div/div[3]/div/div[1]/div[2]").click()
        time.sleep(1)
        # 切换密码登录
        self.driver.find_element(by=By.XPATH,
                                 value=
                                 "//*[@id='dialog-0']/div/div[2]/div/div[3]/div/div[2]/div[2]/div/form/div[3]").click()
        self.driver.implicitly_wait(1)
        # 勾选登录协议
        self.driver.find_element(by=By.XPATH,
                                 value=
                                 "//*[@id='dialog-0']/div/div[2]/div/div[3]/div/div[2]/div[2]/div/form/div[4]/img").click()
        self.driver.implicitly_wait(1)

        self.driver.find_element(By.XPATH,
                                 value="//*[@id='dialog-0']/div/div[2]/div/div[3]/div/div[2]/div[2]/div/form/div[1]/div/div/input").send_keys(
            "13612935690")
        self.driver.find_element(By.XPATH,
                                 "//*[@id='dialog-0']/div/div[2]/div/div[3]/div/div[2]/div[2]/div/form/div[2]/div/div/input").send_keys(
            "Ps@19881103")
        self.driver.find_element(By.XPATH,
                                 "//*[@id='dialog-0']/div/div[2]/div/div[3]/div/div[2]/div[2]/div/form/button").click()
        # 等待登录完成
        self.driver.implicitly_wait(10)
        exec_count = 0
        while exec_count < 15:
            try:
                new_window = self.driver.window_handles[-1]  # 找到新窗口名字
                self.driver.switch_to.window(new_window)  # 切换到最新打开的窗口
                ele_xpath = self.driver.find_element(By.XPATH, "//*[@id='header-user']/div[1]")
                if ele_xpath is None:
                    exec_count += 1
                    continue
                else:
                    exec_count = 16
                print("成功执行第{}次".format(exec_count))
            except WebDriverException as e:
                print("执行失败 :{}".format(e))
                continue
            time.sleep(1)
        self.do_publish(video, desc)

    def do_publish(self, video, desc):
        path = pathlib.Path(video)

        # 视频地址获取
        path_mp4 = ""
        for i in path.iterdir():
            if ".mp4" in str(i):
                path_mp4 = str(i);
                break;

        if path_mp4 != "":
            print("检查到视频路径：" + path_mp4)
        else:
            print("未检查到视频路径，程序终止！")
            exit()

        # 封面地址获取
        path_cover = ""
        for i in path.iterdir():
            if ".png" in str(i) or ".jpg" in str(i):
                path_cover = str(i);
                break;

        if path_cover != "":
            print("检查到封面路径：" + path_cover)
        else:
            print("未检查到封面路径，程序终止！")
            exit()

        self.driver.find_element(By.XPATH, '//*[text()="发布视频"]').click()
        time.sleep(2)
        self.driver.find_element(By.XPATH, '//input[@type="file"]').send_keys(self.path)

        # 等待视频上传完成
        while True:
            time.sleep(3)
            try:
                self.driver.find_element(By.XPATH, '//*[text()="重新上传"]')
                break;
            except Exception as e:
                print("视频还在上传中···")

        print("视频已上传完成！")

        # 添加封面
        self.driver.find_element(By.XPATH, '//*[text()="编辑封面"]').click()
        time.sleep(1)
        self.driver.find_element(By.XPATH, '//div[text()="上传封面"]').click()
        time.sleep(1)
        self.driver.find_element(By.XPATH, '//input[@type="file"]').send_keys(self.path_cover)
        time.sleep(3)
        self.driver.find_element(By.XPATH, '//*[text()="裁剪封面"]/..//*[text()="确定"]').click()
        time.sleep(3)
        self.driver.find_element(By.XPATH,
                                 '//*[text()="设置封面"]/..//*[contains(@class,"upload")]//*[text()="确定"]').click()

        time.sleep(5)
        # 输入视频描述
        self.driver.find_element(By.XPATH, '//div[@aria-autocomplete="list"]//br').send_keys(
            desc + " #上热门 #dou上热门 #我要上热门")

        # 设置选项
        time.sleep(1)
        self.driver.find_element(By.XPATH, '//*[@class="radio--4Gpx6"]').click()
        time.sleep(1)
        self.driver.find_element(By.XPATH, '//*[@class="semi-select-selection"]//span[contains(text(),"输入")]').click()
        time.sleep(1)
        self.driver.find_element(By.XPATH, '//*[@class="semi-select-selection"]//input').send_keys("中关村人工智能科技")
        time.sleep(1)
        self.driver.find_element(By.XPATH, '//*[@class="semi-select-selection"]//input').send_keys("园")
        time.sleep(5)
        self.driver.find_element(By.XPATH,
                                 '//*[@class="semi-popover-content"]//*[text()="中关村人工智能科技园"]').click()

        # 同步到西瓜视频
        time.sleep(1)
        # self.driver.find_element(By.XPATH,'//div[@class="preview--27Xrt"]//input').click()   # 默认启用一次后，后面默认启用了。
        time.sleep(1)
        self.driver.find_element(By.XPATH, '//*[@class="card-pen--2P8rh"]').click()
        time.sleep(1)
        self.driver.find_element(By.XPATH, '//*[@class="DraftEditor-root"]//br').send_keys(desc + " #上热门")
        time.sleep(1)
        self.driver.find_element(By.XPATH, '//button[text()="确定"]').click()

        # 人工进行检查并发布
        # time.sleep(3)
        # # 点击发布
        # self.driver.find_element(By.XPATH,'//button[text()="发布"]').click()


if __name__ == "__main__":
    douyin = Douyin()
    # 基本信息
    # 视频存放路径
    video = r"C:\Users\Jingbit\Desktop\自媒体\剪映\成品\谨防食品中的“五毒”(1)"
    # 视频描述
    desc = "裸眼3D看蜘蛛侠 #搞笑 #电影 #视觉震撼"
    douyin.prepare(video, desc)
